package com.xxl.job.consume.repository;


import com.xxl.job.consume.common.RedisKeyConstant;
import com.xxl.job.consume.model.AlarmInfoModel;
import com.xxl.job.consume.utils.JSONUtils;
import com.xxl.job.consume.utils.MapUtil;
import com.xxl.job.core.log.XxlJobLogger;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Repository;

import java.io.IOException;
import java.util.List;

/**
 * 报警
 */
@Repository
public class AlarmInfoRepository {

    @Autowired
    private StringRedisTemplate redisTemplate;


    /*
     * 查询报警信息
     * @param almCode
     * @return
     */
    public AlarmInfoModel query(String almCode) {

        BoundHashOperations<String, String, String> valueOperations = redisTemplate.boundHashOps(RedisKeyConstant.KEY_HASH_IOT_ACTIVE_ALARM);

        List<String> values = MapUtil.getLikeByMap(valueOperations.entries(), almCode);
        if (null != values && values.size() > 0) {
            for (String value : values) {
                if (StringUtils.isNotBlank(value)) {
                    try {
                        AlarmInfoModel alarmInfoModel = JSONUtils.json2pojo(value, AlarmInfoModel.class);
                        return alarmInfoModel;
                    } catch (IOException e) {
                        XxlJobLogger.log("获取报警信息,终端JSON转换异常！", value, e);
                    }
                }
            }
        }
        return null;
    }

    /**
     * 保存报警信息
     * @param alarmInfoModel
     */
    public void save(AlarmInfoModel alarmInfoModel){
        BoundHashOperations<String, String, String> valueOperations = redisTemplate.boundHashOps(RedisKeyConstant.KEY_HASH_IOT_ACTIVE_ALARM);
        valueOperations.put(alarmInfoModel.getAlmCode(),
                alarmInfoModel.toJson());
    }

    /**
     * 删除报警
     * @param alarmInfoModel
     */
    public void delete(AlarmInfoModel alarmInfoModel){
        String key=alarmInfoModel.getAlmCode();
        BoundHashOperations<String, String, String> valueOperations =redisTemplate.boundHashOps(RedisKeyConstant.KEY_HASH_IOT_ACTIVE_ALARM);
        valueOperations.delete(key);
    }
}
